/**
 * 成就系统工具类
 * 提供成就解锁和管理功能
 */

import { STORAGE_KEYS, getTodayString, getLocalOpenid, formatDate } from './storage.js'

// 成就类型常量
export const ACHIEVEMENT_TYPES = {
  FIRST_DRINK: 'first_drink',         // 第一杯水
  MORNING_DRINK: 'morning_drink',     // 清晨第一杯
  DAILY_GOAL: 'daily_goal',           // 达成日目标
  STREAK_3: 'streak_3',               // 连续3天
  STREAK_7: 'streak_7',               // 连续7天
  TOILET_FIRST: 'toilet_first',       // 第一次如厕
  TOILET_3: 'toilet_3',               // 一天3次如厕
  PERFECT_DAY: 'perfect_day',         // 完美的一天（达成所有目标）
  RANDOM_BONUS: 'random_bonus'        // 随机奖励
}

// 成就配置
const ACHIEVEMENTS = {
  [ACHIEVEMENT_TYPES.FIRST_DRINK]: {
    title: '开启健康生活！',
    description: '记录第一杯水',
    icon: '/static/icons/drink.png',
    energyReward: 1
  },
  [ACHIEVEMENT_TYPES.MORNING_DRINK]: {
    title: '清晨第一杯！',
    description: '9点前喝第一杯水',
    icon: '/static/icons/drink.png',
    energyReward: 2
  },
  [ACHIEVEMENT_TYPES.DAILY_GOAL]: {
    title: '目标达成！',
    description: '完成每日饮水目标',
    icon: '/static/icons/drink.png',
    energyReward: 3
  },
  [ACHIEVEMENT_TYPES.STREAK_3]: {
    title: '坚持不懈！',
    description: '连续3天记录饮水',
    icon: '/static/icons/drink.png',
    energyReward: 3
  },
  [ACHIEVEMENT_TYPES.STREAK_7]: {
    title: '习惯养成！',
    description: '连续7天记录饮水',
    icon: '/static/icons/drink.png',
    energyReward: 5
  },
  [ACHIEVEMENT_TYPES.TOILET_FIRST]: {
    title: '健康排泄！',
    description: '记录第一次如厕',
    icon: '/static/icons/poop.png',
    energyReward: 1
  },
  [ACHIEVEMENT_TYPES.TOILET_3]: {
    title: '排毒高手！',
    description: '一天记录3次如厕',
    icon: '/static/icons/poop.png',
    energyReward: 2
  },
  [ACHIEVEMENT_TYPES.PERFECT_DAY]: {
    title: '完美的一天！',
    description: '达成所有健康目标',
    icon: '/static/icons/dice.png',
    energyReward: 5
  },
  [ACHIEVEMENT_TYPES.RANDOM_BONUS]: {
    title: '意外惊喜！',
    description: '获得随机奖励',
    icon: '/static/icons/dice.png',
    energyReward: 2
  }
}

// 随机成就消息
const RANDOM_ACHIEVEMENTS = [
  { title: '水润肌肤！', description: '饮水有助于皮肤健康', energyReward: 1 },
  { title: '精力充沛！', description: '充足的水分让你更有活力', energyReward: 1 },
  { title: '代谢加速！', description: '饮水促进新陈代谢', energyReward: 1 },
  { title: '头脑清醒！', description: '适量饮水提高注意力', energyReward: 1 },
  { title: '肾脏卫士！', description: '饮水帮助肾脏排毒', energyReward: 2 }
]

/**
 * 获取已解锁的成就
 * @returns {Array} 成就数组
 */
export function getUnlockedAchievements() {
  return uni.getStorageSync('achievements') || []
}

/**
 * 获取所有成就（包括已解锁和未解锁的）
 * @returns {Array} 成就数组
 */
export function getAchievements() {
  const unlockedAchievements = getUnlockedAchievements();
  const allAchievements = [];
  
  // 遍历所有成就类型
  Object.keys(ACHIEVEMENTS).forEach(type => {
    const achievement = ACHIEVEMENTS[type];
    
    // 检查该类型的成就是否已解锁
    const unlocked = unlockedAchievements.some(a => a.type === type);
    
    // 添加到结果数组
    allAchievements.push({
      type: type,
      name: achievement.title,
      description: achievement.description,
      icon: achievement.icon,
      unlocked: unlocked,
      energyReward: achievement.energyReward
    });
  });
  
  // 添加随机成就（只显示已解锁的）
  unlockedAchievements.forEach(achievement => {
    if (achievement.type === ACHIEVEMENT_TYPES.RANDOM_BONUS) {
      allAchievements.push({
        type: achievement.type,
        name: achievement.title,
        description: achievement.description,
        icon: achievement.icon,
        unlocked: true,
        energyReward: achievement.energyReward
      });
    }
  });
  
  return allAchievements;
}

/**
 * 检查成就是否已解锁
 * @param {string} type 成就类型
 * @param {string} date 日期，默认为今天
 * @returns {boolean} 是否已解锁
 */
export function isAchievementUnlocked(type, date = getTodayString()) {
  const achievements = getUnlockedAchievements()
  return achievements.some(a => a.type === type && a.date === date)
}

/**
 * 解锁成就
 * @param {string} type 成就类型
 * @returns {Object|null} 成就对象，如果已解锁则返回null
 */
export function unlockAchievement(type) {
  const today = getTodayString()
  
  // 如果今天已经解锁过这个成就，则不重复解锁
  if (isAchievementUnlocked(type, today)) {
    return null
  }
  
  // 获取成就配置
  let achievement = null
  
  if (type === ACHIEVEMENT_TYPES.RANDOM_BONUS) {
    // 随机选择一个随机成就
    const randomIndex = Math.floor(Math.random() * RANDOM_ACHIEVEMENTS.length)
    const randomAchievement = RANDOM_ACHIEVEMENTS[randomIndex]
    
    achievement = {
      id: `${type}_${Date.now()}`,
      type: type,
      title: randomAchievement.title,
      description: randomAchievement.description,
      icon: ACHIEVEMENTS[type].icon,
      date: today,
      timestamp: Date.now(),
      energyReward: randomAchievement.energyReward
    }
  } else if (ACHIEVEMENTS[type]) {
    achievement = {
      id: `${type}_${Date.now()}`,
      type: type,
      title: ACHIEVEMENTS[type].title,
      description: ACHIEVEMENTS[type].description,
      icon: ACHIEVEMENTS[type].icon,
      date: today,
      timestamp: Date.now(),
      energyReward: ACHIEVEMENTS[type].energyReward
    }
  }
  
  if (achievement) {
    // 保存到已解锁成就列表
    const achievements = getUnlockedAchievements()
    achievements.push(achievement)
    uni.setStorageSync('achievements', achievements)
    
    // 增加能量值
    addEnergy(achievement.energyReward)
    
    return achievement
  }
  
  return null
}

/**
 * 获取当前能量值
 * @returns {number} 能量值
 */
export function getEnergy() {
  return uni.getStorageSync('energy') || 0
}

/**
 * 增加能量值
 * @param {number} amount 增加的能量值
 * @returns {number} 增加后的能量值
 */
export function addEnergy(amount) {
  const currentEnergy = getEnergy()
  const newEnergy = currentEnergy + amount
  uni.setStorageSync('energy', newEnergy)
  return newEnergy
}

/**
 * 消耗能量值
 * @param {number} amount 消耗的能量值
 * @returns {boolean} 是否消耗成功
 */
export function consumeEnergy(amount) {
  const currentEnergy = getEnergy()
  if (currentEnergy >= amount) {
    uni.setStorageSync('energy', currentEnergy - amount)
    return true
  }
  return false
}

/**
 * 检查并解锁饮水相关成就
 * @param {number} currentAmount 当前饮水量
 * @param {number} goalAmount 目标饮水量
 * @returns {Object|null} 解锁的成就，如果没有则返回null
 */
export function checkDrinkAchievements(currentAmount, goalAmount) {
  const now = new Date()
  const hour = now.getHours()
  const achievements = []
  
  // 第一杯水成就
  if (currentAmount === 250) {
    const firstDrink = unlockAchievement(ACHIEVEMENT_TYPES.FIRST_DRINK)
    if (firstDrink) achievements.push(firstDrink)
  }
  
  // 清晨第一杯水
  if (currentAmount === 250 && hour < 9) {
    const morningDrink = unlockAchievement(ACHIEVEMENT_TYPES.MORNING_DRINK)
    if (morningDrink) achievements.push(morningDrink)
  }
  
  // 达成日目标
  if (currentAmount >= goalAmount && currentAmount - 250 < goalAmount) {
    const dailyGoal = unlockAchievement(ACHIEVEMENT_TYPES.DAILY_GOAL)
    if (dailyGoal) achievements.push(dailyGoal)
  }
  
  // 随机奖励 (20%概率)
  if (Math.random() < 0.2) {
    const randomBonus = unlockAchievement(ACHIEVEMENT_TYPES.RANDOM_BONUS)
    if (randomBonus) achievements.push(randomBonus)
  }
  
  return achievements.length > 0 ? achievements : null
}

/**
 * 检查并解锁如厕相关成就
 * @param {number} toiletCount 如厕次数
 * @returns {Object|null} 解锁的成就，如果没有则返回null
 */
export function checkToiletAchievements(toiletCount) {
  const achievements = []
  
  // 第一次如厕
  if (toiletCount === 1) {
    const firstToilet = unlockAchievement(ACHIEVEMENT_TYPES.TOILET_FIRST)
    if (firstToilet) achievements.push(firstToilet)
  }
  
  // 一天3次如厕
  if (toiletCount === 3) {
    const toilet3 = unlockAchievement(ACHIEVEMENT_TYPES.TOILET_3)
    if (toilet3) achievements.push(toilet3)
  }
  
  // 随机奖励 (15%概率)
  if (Math.random() < 0.15) {
    const randomBonus = unlockAchievement(ACHIEVEMENT_TYPES.RANDOM_BONUS)
    if (randomBonus) achievements.push(randomBonus)
  }
  
  return achievements.length > 0 ? achievements : null
}

/**
 * 获取连续打卡天数
 * @returns {number} 连续天数
 */
export function getStreakDays() {
  const streak = uni.getStorageSync('streak') || { count: 0, lastDate: '' }
  const today = getTodayString()
  
  // 如果最后打卡日期是昨天，增加连续天数
  const yesterday = formatDate(new Date(Date.now() - 86400000))
  if (streak.lastDate === yesterday) {
    streak.count += 1
    streak.lastDate = today
    uni.setStorageSync('streak', streak)
  } 
  // 如果最后打卡日期不是昨天也不是今天，重置连续天数
  else if (streak.lastDate !== today) {
    streak.count = 1
    streak.lastDate = today
    uni.setStorageSync('streak', streak)
  }
  
  return streak.count
}

/**
 * 检查并解锁连续打卡成就
 * @returns {Object|null} 解锁的成就，如果没有则返回null
 */
export function checkStreakAchievements() {
  const streakDays = getStreakDays()
  const achievements = []
  
  // 连续3天
  if (streakDays === 3) {
    const streak3 = unlockAchievement(ACHIEVEMENT_TYPES.STREAK_3)
    if (streak3) achievements.push(streak3)
  }
  
  // 连续7天
  if (streakDays === 7) {
    const streak7 = unlockAchievement(ACHIEVEMENT_TYPES.STREAK_7)
    if (streak7) achievements.push(streak7)
  }
  
  return achievements.length > 0 ? achievements : null
}